package org.example.interceptor;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body; // 缓存请求体

    public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 将请求体读入缓存字节数组
        InputStream is = request.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        body = baos.toByteArray(); // 缓存请求体
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 每次返回新的 ByteArrayInputStream，基于缓存的字节数组
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                // Not needed for synchronous reading
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream(), "UTF-8"));
    }

    // 提供一个方法直接获取请求体字符串
    public String getBody() {
        return new String(body, StandardCharsets.UTF_8);
    }
}

